package com.agent.web.report;

import com.agent.page.EasyuiPage;
import com.agent.service.ICustomerSatisfactionService;
import com.agent.util.CommonUtils;
import com.agent.util.DateUtil;
import com.agent.vo.CustomerSatisfactionVO;
import com.agent.vo.RepaireAndSatisVO;
import com.agent.vo.RepaireInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@RequestMapping(value = "/report/customerSatisfaction")
@RestController
@Slf4j
public class CustomerSatisfactionController {

    @Resource(name = "customerSatisfactionService")
    private ICustomerSatisfactionService customerSatisfactionService;

    @RequestMapping(value = "/list",method = RequestMethod.GET)
    public EasyuiPage list(Integer page, Integer rows,RepaireAndSatisVO vo){
        vo.setCurrentName(CommonUtils.encodeStr(vo.getCurrentName()));
        return customerSatisfactionService.getRepaireAndSatis(page,rows,vo);
    }


    @RequestMapping(value = "/export",method = RequestMethod.GET)
    @ResponseBody
    public void export(RepaireAndSatisVO vo, HttpServletResponse response){
        if(!StringUtils.isEmpty(vo.getRingTime())){
            String[] split = vo.getRingTime().split(" - ");
            vo.setBeginDate(DateUtil.parseDate(split[0].concat(" 00:00:00"),DateUtil.DATE_TIME_FORMAT));
            vo.setEndDate(DateUtil.parseDate(split[1].concat(" 23:59:59"),DateUtil.DATE_TIME_FORMAT));
        }
        try (Workbook sheets = customerSatisfactionService.exportExcel(vo); OutputStream output = response.getOutputStream();
             BufferedOutputStream bufferedOutPut = new BufferedOutputStream(output);) {
            // 判断数据
            if(sheets == null) {
                return ;
            }
            // 重置响应对象
            response.reset();
            // 当前日期，用于导出文件名称
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String fileName = "满意度调查-"+sdf.format(new Date())+".xls";
            // 指定下载的文件名--设置响应头
            response.setHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes(),"ISO8859-1"));
//            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            sheets.write(bufferedOutPut);
        }catch (Exception e){
            log.error("export excel error| ",e);
        }
    }

}
